import json
import requests
import random
import sched
import hashlib
import urllib3
import time
from datetime import datetime

today = datetime.today().weekday()  # 获取今天星期几

urllib3.disable_warnings()
# requests.packages.urllib3.disable_warnings()
# =================用户配置  可修改=======================
phone = ""  # 账号
password = ""  # 密码
country = "中国"  # 国家
province = "黑龙江省"  # 省
city = "佳木斯市"  # 城市
address = "向阳区临江花园社区"  # 地址
lat = "46.817953"  # 纬度      115.84851,28.692835
lon = "130.348645"  # 经度
types = "START"  # 类型，START和END，START 上班，END 下班
description = ""
sec = 30  # 随机在0~sec秒执行打卡
isWeekCloak = True  # 周末是否打卡  True 可以  False 不可
isRandomAddress = False  # 随机300m
serveSendKey = ""  # serve酱KEY
# ===================基础变量不建议修改=============================
adminKey = "SCT44520TU2u84Uwc7TooJCNXDNIUw6lz"  # 管理员serve酱KEY


def getNowHour(oldTime):  # 时间换算
    if (oldTime + 8 > 24):
        return oldTime + 8 - 24
    else:
        return oldTime + 8


now_hour = getNowHour(time.gmtime()[3])  # 获取中国时间 小时
typeDec = ''  # 上班类型
# =================脚本配置(不可擅自更改)=======================
inc = random.randint(0, sec)
schedule = sched.scheduler(time.time, time.sleep)
if (isRandomAddress):
    ran = random.uniform(-0.003, 0.003)  # 随机300m坐标
    latitude = str(ran + float(lat))
    longitude = str(ran + float(lon))
else:
    latitude = lat
    longitude = lon
Login_Url = 'https://api.moguding.net:9000/session/user/v1/login'
planUrl = "https://api.moguding.net:9000/practice/plan/v3/getPlanByStu"
saveUrl = "https://api.moguding.net:9000/attendence/clock/v2/save"
salt = "3478cbbc33f84bd00d75d7dfa69e0daa"
token = ""
headers = {
    'Accept-Language': "zh-CN,zh;q=0.8",
    'roleKey': 'student',
    'Host': 'api.moguding.net:9000',
    "Content-Type": "application/json; charset=UTF-8",
    "Cache-Control": "no-cache",
    'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.1; MX4 Build/F2P4MZ) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/41.0.3191.83 Mobile Safari/537.36',
}
if (now_hour < 11):
    types = "START"
    typeDec = '上班'
else:
    types = "END"
    typeDec = '下班'
body = {
    "country": country,
    "address": address,
    "province": province,
    "city": city,
    "latitude": latitude,
    "description": description,
    "type": types,
    "device": "Android",
    "longitude": longitude
}


# ===============================serve酱推送=====================
def sendMsg(key, title, desp):
    url = "https://sctapi.ftqq.com/" + key + ".send"
    body = {
        "title": title,
        "desp": desp
    }
    res = requests.post(url=url, data=body)
    # print(res.text)


# =================生成签名===================
def GenerateSign(x):
    a = x.encode('utf-8')
    a = hashlib.md5(a).hexdigest()
    # print(a)
    return a


# ================登录====================
def login():
    global token, userId, name
    data = {
        "password": password,
        "loginType": "android",
        "uuid": "",
        "phone": phone
    }
    req = requests.post(Login_Url, data=json.dumps(data), headers=headers, verify=False)
    text = req.json()
    new_token = text["data"]["token"]
    name = text["data"]["nikeName"]
    token = json.loads(req.text)['data']['token']
    userId = json.loads(req.text)['data']['userId']


# ===================获取planID=======================
def getPlanId():
    login()

    global planId
    data = {"state": ""}
    print(token)
    headers["Authorization"] = token
    # sign= userId+"student"+salt
    headers["sign"] = GenerateSign(userId + "student" + salt)
    req = requests.post(planUrl, data=json.dumps(data), headers=headers)
    req.headers.keys
    planId = json.loads(req.text)['data'][0]['planId']


# =======================开始打卡=======================
def main():
    getPlanId()

    # sign= device + type + planID + userId + Address + salt
    body["planId"] = planId
    headers["sign"] = GenerateSign(body["device"] + body["type"] + planId + userId + body["address"] + salt)
    req = requests.post(saveUrl, data=json.dumps(body), headers=headers)
    req_json = json.loads(req.text)

    if (req_json["code"] == 200):
        print(name + "打卡成功")
        sendMsg(serveSendKey, "Hi," + name + typeDec + "打卡成功",
                "打卡状态：" + req_json["msg"] + "\n\n打卡地点：" + address + "\n\n打卡时间：" + req_json["data"]["createTime"])
    else:
        print(name + "打卡失败")
        sendMsg(serveSendKey, "蘑菇丁打卡失败", "打卡失败" + "\n\n失败原因：" + req_json["msg"])


def runMain():
    if (isWeekCloak):
        schedule.enter(inc, 0, main, ())
        schedule.run()
    else:
        if (today < 5):
            schedule.enter(inc, 0, main, ())
            schedule.run()
        else:
            print("周末不签到")

try:
    runMain()
except:
    sendMsg(adminKey, phone + '打卡异常', 'gg')
